<template>
	<div>
		<el-dialog title="提示" :visible.sync="dialogVisible" @close='cancel()'
				   :close-on-press-escape="false" :close-on-click-modal="false">
			<el-card class="box-card">
				<div slot="header" class="clearfix">
					<div style="text-align: center">{{ doctor.hospital.hospitalName }}医院处方笺</div>
				</div>
				<div class="text item">
					<span>患者姓名： {{ patientName }}</span>
					<el-divider></el-divider>
					<span>患者年龄： {{ patientBirthDate }}</span>
					<el-divider></el-divider>
					<span>患者性别： {{ patientSex }}</span>
				</div>
			</el-card>
			<el-card class="box-card" style="margin-top: 20px;">
				<div slot="header" class="clearfix">
					<div style="text-align: center">诊断</div>
				</div>
				<div class="text item">
					<el-input v-model="result" placeholder="请输入诊断..." type="textarea" :rows="3"></el-input>
				</div>
			</el-card>
			<el-card class="box-card" style="margin-top: 20px;">
				<div slot="header" class="clearfix">
					<div style="text-align: center">处方药</div>
				</div>
				<div class="text item">
					<el-button type="primary" size="mini" @click="addDrugTable()">加药</el-button>
					<el-table class="addDrug" :data="tableData" style="width: 100%;margin-top:10px;height:300px" border
							  highlight-current-row
							  @current-change="handleCurrentChange"
							  max-height="400"
							  ref="multipleTable">
						<el-table-column label="药品名" width="200">
							<template slot-scope="scope">
								<el-autocomplete
									v-model="scope.row.drugName"
									:fetch-suggestions="querySearchAsync"
									placeholder="请输入内容"
									@select="handleSelect"
									@focus="handleFocus(scope.$index)"
									size="mini"
									:ref="'drugInput' + scope.$index"
								></el-autocomplete>
							</template>
						</el-table-column>
						<el-table-column prop="drug.spec" label="规格" width="70"></el-table-column>
						<el-table-column label="单次用量" width="100">
							<template slot-scope="scope">
								<el-input-number width="80" v-model="scope.row.singleDosage" controls-position="right"
												 :min="1" :max="100" size="mini"></el-input-number>
							</template>
						</el-table-column>
						<el-table-column prop="drug.dosageUnit" label="计量单位" width="80"></el-table-column>
						<el-table-column label="频次" width="120">
							<template slot-scope="scpoe">
								<el-select v-model=" scpoe.row.frequency " size="small">
									<el-option v-for="(item, index) in frequencyOption" :key="index"
											   :label="item.dictLabel" :value="Number(item.dictValue)"></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column prop="days" label="天数" width="100">
							<template slot-scope="scpoe">
								<el-select v-model=" scpoe.row.days" size="mini">
									<el-option v-for="(item, index) in daysOption" :key="index" :label="item.dictLabel"
											   :value="Number(item.dictValue)"></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="用法" width="100">
							<template slot-scope="scpoe">
								<el-select v-model="scpoe.row.usage" size="mini">
									<el-option v-for="(item, index) in usageOption" :key="index" :label="item.dictLabel"
											   :value="Number(item.dictValue)"></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column prop="total" label="总量" width="100">
							<template slot-scope="scpoe">
								<el-input-number v-model="scpoe.row.total" controls-position="right" :min="1" :max="100"
												 size="mini"></el-input-number>
							</template>
						</el-table-column>
						<el-table-column label="单位" width="60">
							<template slot-scope="scpoe">
								{{ retailFilter(scpoe.row.drug.retailUnit) }}
							</template>
						</el-table-column>
						<el-table-column prop="entrust" label="嘱托" width="140">
							<template slot-scope="scpoe">
								<el-select v-model=" scpoe.row.entrust " size="mini">
									<el-option v-for="(item, index) in entrustOption" :key="index"
											   :label="item.dictLabel" :value="item.dictValue.toString()"></el-option>
								</el-select>
							</template>
						</el-table-column>
						<div slot="empty">
							<svg-icon icon-class="no-data" class-name='no-data-class'/>
							<br><span style="font-size: 30px;">暂无数据</span></div>
					</el-table>
				</div>
			</el-card>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="addPrescriptionInfoTable">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import {GetDoctorByUserId} from '@/api/doctor'
import {AddPrescribe} from '@/api/order/inquriy'

import {GetDrugTypeList, AddPreDrug} from '@/api/drug/drug'
import {GetDrugAll, GetDrugId} from "@/api/doctor/drug";
import {mapGetters} from 'vuex'

export default {
	props: {
		patientId: {},
		patientName: {},
		patientSex: {},
		patientBirthDate: {},
		illnessDescId: {},
		doctorId: {}
	},
	data() {
		return {
			dialogVisible: true,
			doctor: {
				hospital: {}
			},
			result: '',
			tableData: [],
			frequencyOption: [],
			daysOption: [],
			usageOption: [],
			entrustOption: [],
			retailOption: [],
			nameArr: [],
		};
	},
	computed: {
		...mapGetters(['userid']),
		retailFilter(text) {
			return ((text) => {
				for (let i = 0; i < this.retailOption.length; i++) {
					if (this.retailOption[i].dictValue == text) {
						return this.retailOption[i].dictLabel;
					}
				}
			})
		},
	},
	mounted() {
		this.getDoctor();
		this.getDrug();
		this.getDicts('default_frequency').then(res => {
			this.frequencyOption = res.data
		})
		this.getDicts('drug_days').then(res => {
			this.daysOption = res.data
		})
		this.getDicts('default_usage').then(res => {
			this.usageOption = res.data
		})
		this.getDicts('doctor_entrust').then(res => {
			this.entrustOption = res.data
		})
		this.getDicts('retail_unit').then(res => {
			this.retailOption = res.data
		})
	},

	methods: {
		handleCurrentChange(val) {
			this.prescriptionInfo = val;
			if (val.id != '') {
				GetDrugId({id: val.drug.id}).then(res => {
					this.drugArr = res.drug[0]
					this.drugInfoFlag = true
				})
			} else {
				this.drugInfoFlag = false
			}
		},
		handleSelect(item) {
			console.log(item)
			this.tableData[this.currentIndex].dosageUnit = item.dosageUnit
			this.tableData[this.currentIndex].retailUnit = item.retailUnit
			this.tableData[this.currentIndex].spec = item.spec
			this.tableData[this.currentIndex].drugId = item.drugId
		},
		handleFocus(index) {
			this.currentIndex = index;
		},
		addDrugTable() {
			var list = {
				id: '',
				drugName: '',
				days: '',
				total: '',
				entrust: '',
				frequency: '',
				singleDosage: '',
				drug: {
					id: '',
					spec: '',
					retailUnit: '',
					dosageUnit: ''
				},
			}
			this.tableData.push(list)
			let refInput = 'drugInput' + (this.tableData.length - 1);
			setTimeout(() => {
				this.$refs[refInput].focus();
			}, 100)

			this.$refs.multipleTable.setCurrentRow(this.tableData[this.tableData.length - 1]);
		},
		getDrug() {
			GetDrugAll().then(res => {
				res.drug.forEach((item, index) => {
					let drugParam = {
						value: item.name,
						pinyin: item.pinyin,
						drugId: item.drugId,
						spec: item.spec,
						dosageUnit: item.dosageUnit,
						retailUnit: item.retailUnit
					}
					this.nameArr.push(drugParam)
				})
			})
		},
		querySearchAsync(queryString, cb) {
			let restaurants = this.nameArr;
			let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
			clearTimeout(this.timeout);
			this.timeout = setTimeout(() => {
				cb(results);
			}, 0);
		},
		createStateFilter(queryString) {
			return (state) => {
				return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
					|| (state.pinyin.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
			};
		},
		addPrescriptionInfoTable() {
			let params = {
				doctorId: this.doctorId,
				patientId: this.patientId,
				illnessDescId: this.illnessDescId,
				result: this.result,
				auditStatus: 0
			}

			AddPrescribe(params).then(res => {
				let arr = JSON.parse(JSON.stringify(this.tableData))
        for (let i = 0; i < arr.length; i++) {
          this.addPrescriptionInfo(arr[i], i, arr.length - 1, res.data)
        }
				this.$emit('close', res.data);
			});
		},
		// 添加处方明细
		addPrescriptionInfo(item, i, length, prescribeId) {
			let formInfos = {
				drugId: item.drugId,
				prescribeId: prescribeId,
				drugUnit: item.total,
				frequency: item.frequency,
				medicationDays: item.days,
				medicationUsage: item.usage,
				singleUnit: item.singleDosage,
				unitPrice: item.retailPrice
			}
			AddPreDrug(formInfos).then(res => {
				console.log(res)
			})
			if (formInfos.drugId == '') {
				this.$message.warning("请填选药品")
				return
			} else if (formInfos.singleDosage == '') {
				this.$message.warning("请填写单次用量")
				return
			} else if (formInfos.frequency === '') {
				this.$message.warning("请填写频次")
				return
			} else if (formInfos.days === '') {
				this.$message.warning("请填写天数")
				return
			} else if (formInfos.usage === '') {
				this.$message.warning("请填写用法")
				return
			} else if (formInfos.total === '') {
				this.$message.warning("请填写总量")
				return
			} else if (formInfos.entrust === '') {
				this.$message.warning("请填写嘱托")
				return
			}
		},
		getDoctor() {
			GetDoctorByUserId({userId: this.userid}).then(res => {
				this.doctor = res.data;
			})
		},

		cancel() {
			this.$emit('close')
		}
	}
}
</script>

<style lang="scss" scoped>

</style>
